import { contextBridge, ipcRenderer } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';
import { bridgeKeys } from '/src/renderer/src/utils/dicts';

/*预加载*/

// 渲染器中的自定义api
const preloadApi = {
  quitApp: () => ipcRenderer.send(bridgeKeys.quit), // 退出应用
  startDownload: () => ipcRenderer.send(bridgeKeys.startDownload), // 立即更新
  changeCacheDirectory: () => ipcRenderer.invoke(bridgeKeys.changeCacheDirectory), // 打开更改缓存目录的弹框
  clearCache: () => ipcRenderer.invoke(bridgeKeys.clearCache), // 清除缓存
  getCachePath: (cb = () => {}) => ipcRenderer.on(bridgeKeys.getCachePath, cb), // 获取缓存的路径
  quitAndInstall: () => ipcRenderer.send(bridgeKeys.quitAndInstall), // 退出并安装
};

// 使用`contextBridge` API将Electron API暴露
// 仅当启用了上下文隔离时才渲染器，否则只需添加到DOM全局
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI);
    contextBridge.exposeInMainWorld('preloadApi', preloadApi);
  } catch (error) {
    console.error(error);
  }
} else {
  window.electron = electronAPI;
  window.api = preloadApi;
}
